package project.dao.impl;

import project.bean.RecordBean;
import project.bean.UserBean;
import project.dao.IRecordDAO;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class RecordDAOImpl extends BaseDAO implements IRecordDAO {
    /**
     * 通过结果集填充一个交易记录对象
     *
     * @return 返回交易记录实例
     */
    private RecordBean getRecord() throws SQLException {
        RecordBean recordBean = new RecordBean(rs.getString("r_userId"), null, 0);
        recordBean.setId(rs.getString("pk_id"));
        recordBean.setDate(LocalDate.parse(rs.getString("r_date")));
        recordBean.setDescription(rs.getString("r_description"));
        recordBean.setBalance(rs.getDouble("r_balance"));

        return recordBean;

    }

    /**
     * 插入交易记录
     *
     * @param recordBean
     */
    @Override
    public void insert(RecordBean recordBean) {
        this.setConnection();
        String sql = "insert into t_record(r_userId,r_date,r_description,r_balance) value (?,?,?,?)";
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, recordBean.getUser().getId());
            ps.setObject(2, recordBean.getDate());
            ps.setObject(3, recordBean.getDescription());
            ps.setObject(4, recordBean.getBalance());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection();
        }
    }

    /**
     * 通过用户账号获取交易记录
     *
     * @param userId 用户账号
     * @return 用户交易记录集合
     */
    @Override
    public List<RecordBean> getRecordsByUserId(String userId) {
        this.setConnection();
        String sql = "select * from t_record where r_userId=?";
        List<RecordBean> list = new ArrayList();
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, userId);
            rs = ps.executeQuery();
            while(rs.next()){
                RecordBean recordBean = getRecord();
                list.add(recordBean);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection();
        }
        return list;
    }
}
